package com.example.zzh.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.zzh.utils.MyClass;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zzh.entity.*;
import com.example.zzh.service.*;
import com.example.zzh.utils.Result;
import com.example.zzh.utils.ResultGenerator;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.text.html.parser.Entity;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 单据主表 前端控制器
 * </p>
 *
 * @author zzh
 * @since 2023-08-21
 */
@RestController
@RequestMapping("/zzh-depot-head")
public class ZzhDepotHeadController {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ZzhDepotHeadService zzhDepotHeadService;

    @Autowired
    private ZzhDepotItemService zzhDepotItemService;

    @Autowired
    private ZzhUserService zzhUserService;

    @Autowired
    private ZzhDepotService zzhDepotService;

    @Autowired
    private ZzhProductService zzhProductService;
    @Autowired
    private ZzhProductStockService zzhProductStockService;

    @Autowired
    private ZzhStaffService zzhStaffService;

    @PostMapping("/option")
    @ApiOperation(value = "查询供应商|客户列表", notes = "查询下拉供应商|客户列表")
    public Result option(@RequestBody Map<String,Object> params){
        Map<String,Object> data=new HashMap<>();
        if(!StringUtils.isEmpty(params.get("type")) && params.get("type")!=null ){
            if(params.get("type").equals("供应商")){
                List<ZzhUser> zzhUsers=zzhUserService.lambdaQuery().eq(ZzhUser::getType,"供应商").eq(ZzhUser::getStatus,1).list();
                Map<Long,String> hashMapUsers=new HashMap<Long, String>();
                for (ZzhUser i : zzhUsers) {
                    hashMapUsers.put(i.getId(),i.getName());
                }
                data.put("hashMapUsers",hashMapUsers);
            }
            if(params.get("type").equals("客户")){
                List<ZzhUser> zzhUsers=zzhUserService.lambdaQuery().eq(ZzhUser::getType,"客户").eq(ZzhUser::getStatus,1).list();
                Map<Long,String> hashMapUsers=new HashMap<Long, String>();
                for (ZzhUser i : zzhUsers) {
                    hashMapUsers.put(i.getId(),i.getName());
                }
                data.put("hashMapUsers",hashMapUsers);
            }
        }else {
            return ResultGenerator.genFailResult("参数异常！");
        }
        if(!StringUtils.isEmpty(params.get("depot")) && params.get("depot")!=null ){
            List<ZzhDepot> zzhDepots=zzhDepotService.lambdaQuery().eq(ZzhDepot::getStatus,1).list();
            Map<Long,String> hashMapDepots=new HashMap<Long, String>();
            for (ZzhDepot i : zzhDepots) {
                hashMapDepots.put(i.getId(),i.getName());
            }
            data.put("hashMapDepots",hashMapDepots);
        }
        return ResultGenerator.genSuccessResult(data);
    }

    @PostMapping("/list")
    @ApiOperation(value = "查询所有订单分页", notes = "分页")
    public Result list(@RequestBody Map<String,Object> params) {
        if (StringUtils.isEmpty(params.get("page")) || StringUtils.isEmpty(params.get("limit"))) {
            return ResultGenerator.genFailResult("参数异常！");
        }
        Page<ZzhOrder> page=new Page<>();
        page.setCurrent((int) params.get("page"));
        page.setSize((int) params.get("limit"));
        HashMap<String,Object> hashMap=new HashMap<>();
        IPage r=null;
        if(!StringUtils.isEmpty(params.get("number"))){
            hashMap.put("number",params.get("number"));
        }
        if(!StringUtils.isEmpty(params.get("status"))){
            hashMap.put("status",params.get("status"));
        }
        if(!StringUtils.isEmpty(params.get("type"))){
            hashMap.put("type",params.get("type"));
        }
        hashMap.put("subType",params.get("subType"));
        r=zzhDepotHeadService.pageNumber(page,hashMap);

        ArrayList<ZzhOrder> arrayList=new ArrayList<>();
        for(Object Obj: r.getRecords()){
            ZzhOrder zzhOrder=(ZzhOrder) Obj;
            zzhOrder.setCurrentNumber(zzhProductStockService.selectCurrentNumber(zzhOrder.getMaterialId()));
            if(!StringUtils.isEmpty(zzhOrder.getMaterialId()) && zzhOrder.getMaterialId()!=null ){
                ZzhProduct zzhProduct=zzhProductService.getProductById(zzhOrder.getMaterialId());
                zzhOrder.setMaterialName(zzhProduct.getName());
                List<ZzhProductStock> zzhProductStocks=zzhProductStockService.lambdaQuery().eq(ZzhProductStock::getMaterialId,zzhOrder.getMaterialId()).list();
                zzhOrder.setZzhProductStock(zzhProductStocks);
            }
            if(!StringUtils.isEmpty(zzhOrder.getCreator()) && zzhOrder.getCreator()!=null ){
                ZzhStaff zzhStaff=zzhStaffService.getRoleById(zzhOrder.getCreator());
                zzhOrder.setCreatorName(zzhStaff.getUsername());
            }
            if(!StringUtils.isEmpty(zzhOrder.getOrganId()) && zzhOrder.getOrganId()!=null ){
                ZzhUser zzhUser=zzhUserService.getById(zzhOrder.getOrganId());
                zzhOrder.setOrganName(zzhUser.getName());
            }
            arrayList.add(zzhOrder);
        }
        return ResultGenerator.genSuccessResult(arrayList,r.getTotal());
    }

    @Transactional
    @PostMapping("/add")
    @ApiOperation(value = "新增订单", notes = "新增订单")
    public Result add(@RequestBody ZzhOrder zzhOrder){
        System.out.println("zzhOrder"+zzhOrder.toString());
        // 获取Session对象
        HttpSession session = request.getSession();
        // 将用户信息存储到Session中
        ZzhStaff zzhStaff=(ZzhStaff) session.getAttribute("user");
        //判断Session是否为空
        if(zzhStaff!=null){
            zzhOrder.setCreator(zzhStaff.getId());
        }
        //查看商品是否为空
        if(zzhOrder.getMaterialId()==null){
            return ResultGenerator.genErrorResult(404,"新增不成功 请选择商品");
        }
        zzhOrder.setStatus("0");
        zzhOrder.setDeleteFlag("0");
        zzhOrder.setSource("0");
        MyClass myClass=new MyClass();
        Boolean flag=false;
        ZzhDepotHead zzhDepotHead=new ZzhDepotHead();
        myClass.mapBtoA(zzhOrder,zzhDepotHead); //zzhOrder转换成zzhDepotHead类
        //判断票据号是否为空，为空就新增不成功
        if(zzhDepotHeadService.selectId(zzhOrder.getNumber())== null){
            //新增
            Long i=zzhDepotHeadService.saveDepotHead(zzhDepotHead);
            //新增一条数据就为成功
            if(i==1){
                flag=true;
            }else {
                return ResultGenerator.genErrorResult(404,"新增不成功 非唯一编号");
            }
        }else {
            return ResultGenerator.genErrorResult(404,"新增不成功 票据为空");
        }

        if(flag){
            Long id=zzhDepotHeadService.selectId(zzhOrder.getNumber());
            ZzhDepotItem zzhDepotItem=new ZzhDepotItem();
            myClass.mapBtoA(zzhOrder,zzhDepotItem);
            zzhDepotItem.setHeaderId(id);
            zzhDepotItem.setBasicNumber(zzhDepotItem.getOperNumber());
            if(!zzhDepotItemService.save(zzhDepotItem)){
                return ResultGenerator.genErrorResult(404,"新增不成功 子订单");
            }
        }
        if(flag){
            return ResultGenerator.genSuccessResult();
        }else {
            return ResultGenerator.genErrorResult(404,"新增不成功");
        }
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改订单", notes = "修改订单")
    public Result mod(@RequestBody ZzhOrder zzhOrder){
        // 获取Session对象
        HttpSession session = request.getSession();
        // 将用户信息存储到Session中
        ZzhStaff zzhStaff=(ZzhStaff) session.getAttribute("user");
        //判断Session是否为空
        if(zzhStaff!=null){
            zzhOrder.setCreator(zzhStaff.getId());
        }
        zzhOrder.setStatus("0");
        zzhOrder.setDeleteFlag("0");
        zzhOrder.setSource("0");
        MyClass myClass=new MyClass();
        Boolean flag=false;
        ZzhDepotHead zzhDepotHead=new ZzhDepotHead();
        if(zzhOrder.getId()!=null){
            myClass.mapBtoA(zzhOrder,zzhDepotHead);
            if(!zzhDepotHeadService.updateById(zzhDepotHead)){
                return ResultGenerator.genErrorResult(404,"订单Head 修改不成功");
            }
        }else {
            return ResultGenerator.genErrorResult(404,"订单无ID 修改不成功");
        }
        if(zzhOrder.getMaterialId()!=null && zzhOrder.getMaterialId()!='0'){
            ZzhDepotItem zzhDepotItem=new ZzhDepotItem();
            myClass.mapBtoA(zzhOrder,zzhDepotItem);
            zzhDepotItem.setHeaderId(zzhDepotHead.getId());
            zzhDepotItem.setBasicNumber(zzhDepotItem.getOperNumber());
            Long id=zzhDepotItemService.selectId(zzhDepotHead.getId());
            zzhDepotItem.setId(id);
            if(!zzhDepotItemService.updateById(zzhDepotItem)){
                return ResultGenerator.genErrorResult(404,"订单Item 修改不成功");
            }
        }else {
            return ResultGenerator.genErrorResult(404,"订单无商品ID 修改不成功");
        }
        return ResultGenerator.genSuccessResult();
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除订单", notes = "删除订单")
    public Result delete(@RequestParam Long id){
        ZzhDepotHead zzhDepotHead=zzhDepotHeadService.getById(id);
        if(!Objects.isNull(zzhDepotHead)){
            zzhDepotHead.setDeleteFlag("1");
            if(zzhDepotHeadService.updateById(zzhDepotHead)) {
                return ResultGenerator.genSuccessResult();
            }
            return ResultGenerator.genErrorResult(404,"删除不成功");
        }else {
            return ResultGenerator.genErrorResult(404,"删除不成功");
        }
    }

    @Transactional
    @PutMapping("/updateStatus")
    @ApiOperation(value = "修改订单状态", notes = "修改订单状态")
    public Result updateStatus(@RequestBody Map<String,Object> params){
        if (!StringUtils.isEmpty(params.get("materialId")) && !StringUtils.isEmpty(params.get("depotId"))) {
            LambdaQueryWrapper<ZzhProductStock> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ZzhProductStock::getMaterialId, params.get("materialId"))
                    .eq(ZzhProductStock::getDepotId,params.get("depotId"));
            //查询商品和仓库信息
            ZzhProductStock zzhProductStock=zzhProductStockService.getOne(queryWrapper);
            if(!Objects.isNull(zzhProductStock)){
                if(params.get("type").equals("入库")){
                    BigDecimal operNumber = new BigDecimal(params.get("operNumber").toString());
                    zzhProductStock.setCurrentNumber(zzhProductStock.getCurrentNumber().add(operNumber));
                }
                if(params.get("type").equals("出库")){
                    BigDecimal operNumber = new BigDecimal(params.get("operNumber").toString());
                    if(zzhProductStock.getCurrentNumber().compareTo(operNumber)>0){
                        zzhProductStock.setCurrentNumber(zzhProductStock.getCurrentNumber().subtract(operNumber));
                    }else {
                        return ResultGenerator.genErrorResult(404,"更新不成功 库存不足");
                    }
                }
                if(!zzhProductStockService.updateById(zzhProductStock)){
                    return ResultGenerator.genErrorResult(404,"更新不成功 库存");
                }
            }
        }
        //查询订单信息
        ZzhDepotHead zzhDepotHead=zzhDepotHeadService.getById(params.get("id").toString());
        if(!Objects.isNull(zzhDepotHead)){
            System.out.println("---------------------1");
            //判断是否关联订单号
            if(!StringUtils.isEmpty(zzhDepotHead.getLinkNumber()) && zzhDepotHead.getLinkNumber()!=null ){
                ZzhDepotHead zzhDepotHead1=zzhDepotHeadService.selectDepotHead(zzhDepotHead.getLinkNumber());
                if(zzhDepotHead1!=null){
                    zzhDepotHead1.setStatus("2");
                    if(!zzhDepotHeadService.updateById(zzhDepotHead1)){
                        return ResultGenerator.genErrorResult(404,"更新不成功 链接订单状态");
                    }
                }
            }
            if(zzhDepotHead.getStatus().equals("0")){
                zzhDepotHead.setStatus("1");
            }
            if(zzhDepotHeadService.updateById(zzhDepotHead)) {
                return ResultGenerator.genSuccessResult();
            }
            return ResultGenerator.genErrorResult(404,"更新不成功 订单状态");
        }else {
            return ResultGenerator.genErrorResult(404,"更新不成功");
        }
    }

    @PostMapping("/findeByNumber")
    @ApiOperation(value = "查询是否重复", notes = "查询是否重复")
    public Result findeByLoginName(@RequestParam String number){
        List list=zzhDepotHeadService.lambdaQuery().eq(ZzhDepotHead::getNumber,number).list();
        return list.size()>0?ResultGenerator.genSuccessResult(list):ResultGenerator.genFailResult("不重复");
    }
}